package ezXpns.analysis;

import java.awt.Color;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;
/**
 * Creates a pie-chart for analysis feature
 *
 */

//@author A0086931X
public class PieChart extends JPanel {

	public PieChart(String title) {
		setTitle(title);
		result = new DefaultPieDataset();
	}

	public void refreshPie() {
		if(chartPanel!=null)remove(chartPanel);
		JFreeChart chart = createChart(result, chartTitle);       
		chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(320,270));	
		chart.setBackgroundPaint(new Color(0, 0, 0, 0)); // transparent black
		chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 16));
		chart.getTitle().setHorizontalAlignment(org.jfree.ui.HorizontalAlignment.LEFT);
		
		add(chartPanel);
	}


	public void addData(String name, float value) {
		result.setValue(name, value);
	}
	
	public void inputData(HashMap<String,Float> data){
		result = new DefaultPieDataset();
		for(Entry<String, Float> entry : data.entrySet()) {
		    addData(entry.getKey(), entry.getValue());
		}
	}
	
	public void setTitle(String title) {
		chartTitle = title;
	}

	private JFreeChart createChart(PieDataset dataset, String title) {
		JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, true, true);

		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setStartAngle(290);
		plot.setDirection(Rotation.CLOCKWISE);
		plot.setForegroundAlpha(0.5f);
		return chart;
	}
	
	private static final long serialVersionUID = 1L;
	private String chartTitle;
	private DefaultPieDataset result ;
	private ChartPanel chartPanel;
}